package hsp.admin.app.literature.aop;

import hsp.admin.app.literature.service.IUpCountService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Optional;

@Aspect
@Component
public class UpCountAop {

    private final IUpCountService upCountService;

    @Autowired
    public UpCountAop(IUpCountService upCountService) {
        this.upCountService = upCountService;
    }

    @After("@annotation(hsp.admin.app.literature.aop.UpCountDelete)")
    public void afterController(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        UpCountDelete annotation = method.getAnnotation(UpCountDelete.class);
        Optional.ofNullable(annotation).ifPresent(ele -> {
            Object[] args = joinPoint.getArgs();
            Long literatureId = Long.parseLong(args[0].toString());
            String type = annotation.value().name();
            upCountService.deleteByLiteratureIdAndType(literatureId, type);
        });
    }
}
